package com.design.memento.multistate;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.HashMap;

/**
 * @ClassName BeanUtils.java
 * @Description BeanUtils工具类
 * @author Jon
 * @date 2018年6月20日 下午5:48:08
 */
public class BeanUtils {
	/**   
	 * Description  	把bean的所有属性及数值放入到Hashmap中	
	 */ 
	public static HashMap<String, Object> backupProp(Object bean) {
		HashMap<String, Object> result = new HashMap<String, Object>();
		try {
			//获得bean描述
			BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass());
			//获得属性描述
			PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
			//遍历所有属性
			for (PropertyDescriptor des : descriptors) {
				String fieldName = des.getName();
				Method getter = des.getReadMethod();
				Object fieldValue = getter.invoke(bean, new Object[]{});
				if (!fieldName.equalsIgnoreCase("class")) {
					result.put(fieldName, fieldValue);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	/**   
	 * Description  	把Hashmap中的值返回到bean中	
	 */ 
	public static void restoreProp(Object bean, HashMap<String, Object> propMap) {
		try {
			//获得bean描述
			BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass());
			//获得属性描述
			PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
			//遍历所有属性
			for (PropertyDescriptor des : descriptors) {
				String fieldName = des.getName();
				if (propMap.containsKey(fieldName)) {
					Method setter = des.getWriteMethod();
					setter.invoke(bean, new Object[]{propMap.get(fieldName)});
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
